package com.springboot.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author peter
 * @title: Test1DatasourceConfig
 * @projectName springAll-peter
 * @description: TODO
 * @date 19-5-5下午5:30
 */

@Configuration
@MapperScan(basePackages = Test1DatasourceConfig.PACKAGE, sqlSessionFactoryRef = "test1SqlSessionFactory")
public class Test1DatasourceConfig {

    //test1dao扫描路径
    static final String PACKAGE = "com.springboot.test1dao";

    // mybatis mapper扫描路径
    static final String MAPPER_LOCATION = "classpath:mapper/test1/*.xml";

    @Primary
    @Bean(name = "test1datasource")
    @ConfigurationProperties("spring.datasource.druid.mysql.test1")
    public DataSource test1DataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "test1TransactionManager")
    @Primary
    public DataSourceTransactionManager test1TransactionManager() {
        return new DataSourceTransactionManager(test1DataSource());
    }


    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1datasource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        //如果不使用xml的方式配置mapper，则可以省去下面这行mapper location的配置。
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(Test1DatasourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }


}
